package io.sundial.console.datasource.core;

import com.zaxxer.hikari.HikariDataSource;

import java.sql.SQLException;

/**
 * 数据源类型
 *
 * @author Payne 646742615@qq.com
 * 2019/1/3 15:21
 */
public enum DatasourceType {

    MySQL {
        @Override
        public void verify(Datasource datasource) throws SQLException {
            try (HikariDataSource hds = new HikariDataSource()) {
                hds.setJdbcUrl(String.format("jdbc:mysql://%s/%s", datasource.getAddress(), datasource.getCatalog()));
                hds.setUsername(datasource.getUsername());
                hds.setPassword(datasource.getPassword());
                hds.getConnection().createStatement().execute("SELECT 1");
            }
        }
    },

    SQLServer {
        @Override
        public void verify(Datasource datasource) throws SQLException {
            try (HikariDataSource hds = new HikariDataSource()) {
                hds.setJdbcUrl(String.format("jdbc:sqlserver://%s;database=%s", datasource.getAddress(), datasource.getCatalog()));
                hds.setUsername(datasource.getUsername());
                hds.setPassword(datasource.getPassword());
                hds.getConnection().createStatement().execute("SELECT 1");
            }
        }
    },

    Oracle {
        @Override
        public void verify(Datasource datasource) throws SQLException {
            try (HikariDataSource hds = new HikariDataSource()) {
                hds.setJdbcUrl(String.format("jdbc:oracle:thin:@//%s/%s", datasource.getAddress(), datasource.getCatalog()));
                hds.setUsername(datasource.getUsername());
                hds.setPassword(datasource.getPassword());
                hds.getConnection().createStatement().execute("SELECT 1 FROM DUAL");
            }
        }
    };

    public abstract void verify(Datasource datasource) throws SQLException;
}
